# coding=utf-8

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models import models
from utils.enums import Struct
from utils.htmlutils import setXmlType
import logging


class NoteHandler(webapp.RequestHandler):

    def __init__(self):
        logging.info('init ' + str(self.__class__))
        self.note_template = 'templates/main/note.xml'
        self.struct = Struct()
        self.struct.user = users.get_current_user()

    def _new(self):
        self.struct.note = models.create_note(self.user, 'Title of the new note', 'Sample')
        self.struct.note.edit = True
        self.response.out.write(template.render(self.note_template, self.struct._compile()))

    def _edit(self):
        id = self.request.get('id')
        if not id:
            self.response.set_status(400, 'Bad Request')
            return
        self.struct.note = models.get_note(id)
        if not self.struct.note:
            self.response.set_status(400, 'Bad Request')
            return
        self.struct.note.edit = True
        self.response.out.write(template.render(self.note_template, self.struct._compile()))

    def _remove(self):
        id = self.request.get('id')
        if not id:
            self.response.set_status(400, 'Bad Request')
            return

        models.remove_note(id)



    def _apply(self):
        id = self.request.get('id')
        title = self.request.get('title')
        text = self.request.get('note')

        if not title or not text or not id:
            self.response.set_status(400, 'Bad Request')
            return

        self.struct.note = models.get_note(id)
        if not self.struct.note:
            self.response.set_status(400, 'Bad Request')
            return

        self.struct.note.title = title
        self.struct.note.note = text
        self.struct.note.put()
        self.response.out.write(template.render(self.note_template, self.struct._compile()))

    def post(self):
        self.user = users.get_current_user()
        if None == self.user:
            self.response.set_status(403, 'Forbidden')
            return

        action = self.request.get('action')
        if None == action:
            self.response.set_status(400, 'Bad Request')
            return

        setXmlType(self.response)

        if action == 'new':
            self._new()
        elif action == 'edit':
            self._edit()
        elif action == 'apply':
            self._apply()
        elif action == 'remove':
            self._remove()


